import axios from 'axios';

let http = axios.create({
    baseURL: baseurl,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    },
    transformRequest: [function (data) {
        let newData = '';
        for (let k in data) {
            if (data.hasOwnProperty(k) === true) {
                newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
            }
        }
        return newData;
    }]
});

http.interceptors.response.use(

    // 请求成功
    res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res),
    // 请求失败
    error => {
        const { response } = error;
        if (response) {
            // 请求已发出，但是不在2xx的范围
            errorHandle(response.status, response.data.message);
            return Promise.reject(response);
        } else {
            // 处理断网的情况
            // eg:请求超时或断网时，更新state的network状态
            // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
            // 关于断网组件中的刷新重新获取数据，会在断网组件中说明
            store.commit('changeNetwork', false);
        }
});

const errorHandle = (status, other) => {
    // 状态码判断
    switch (status) {
    // 401: 未登录状态，跳转登录页   
        case 401:
        console('去登录');
        break;
    // 403 token过期
    // 清除token并跳转登录页
        case 403:
        console('登录过期，请重新登录');
        
       break;
   // 404请求不存在
        case 404:
        console('请求的资源不存在');
      break;
      default:
      console.log(other);
}}

function apiAxios(method, url, params, response) {
    http({
        method: method,
        url: url,
        data: method === 'POST' || method === 'PUT' ? params : null,
        params: method === 'GET' || method === 'DELETE' ? params : null,
    }).then(function (res) {
        response(res);
    }).catch(function (err) {
        response(err);
    })
}

export default {
    get: function (url, params, token = "", response, ) {
        if (token != "") {
            console.log("重新设置",token);
            http.defaults.headers.common['Authorization'] = "bearer " + token;
        }
        //  http.defaults.headers.common['Authorization'] = "bearer " + token;
        return apiAxios('GET', url, params, response)
    },
    post: function (url, params, response) {

        http.defaults.headers.common['Authorization'] = "Basic ZmViczoxMjM0NTY=";
        return apiAxios('POST', url, params, response)
    },
    post2: function (url, params, response) {

        http.defaults.headers.common['Authorization'] = "";
        return apiAxios('POST', url, params, response)
    },
    put: function (url, params, response) {
        return apiAxios('PUT', url, params, response)
    },
    delete: function (url, params, response) {
        return apiAxios('DELETE', url, params, response)
    },

}